define([
    "esri/layers/WebTiledLayer",
    "esri/geometry/Point",
    "esri/geometry/webMercatorUtils",
    "esri/request",
    "esri/symbols/SimpleMarkerSymbol",
    "esri/Color",
    "esri/tasks/FindTask",
    "esri/tasks/FindParameters",
    "esri/tasks/FindResult",
    "dojo/_base/array",
    "esri/InfoTemplate",
    "esri/tasks/query",
    "esri/layers/FeatureLayer",
    "esri/graphic",
    "esri/toolbars/draw",
    "esri/tasks/GeometryService",
    "esri/tasks/LengthsParameters",
    "esri/tasks/AreasAndLengthsParameters"

], function (WebTiledLayer,Point, webMercatorUtils,esriRequest,SimpleMarkerSymbol,Color,FindTask,FindParameters,FindResult,array,InfoTemplate, Query,FeatureLayer,Graphic,Draw,GeometryService,LengthsParameters,AreasAndLengthsParameters) {

    var exports = {
        loadBaseMap : function(map) {
            var layer = new WebTiledLayer('http://${subDomain}.tianditu.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=${col}&TILEROW=${row}&TILEMATRIX=${level}',{
                subDomains: ['t0','t1','t2','t3','t4','t5','t6','t7']
            })
            //中文注记
            var annolayer = new WebTiledLayer("http://${subDomain}.tianditu.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=${col}&TILEROW=${row}&TILEMATRIX=${level}",{
                subDomains: ['t0','t1','t2','t3','t4','t5','t6','t7']
            });
            map.addLayers([layer,annolayer]);
            return map;
        },
        centerAt: function(map, x, y) {
            var pt = new Point(x,y,map.spatialReference)
            var newPt = webMercatorUtils.geographicToWebMercator(pt)
            map.centerAt(newPt);
        },
        mercatorCenterAt: function (map, x, y) {
            var pt = new Point(x,y,map.spatialReference);
            map.centerAt(pt);
        },
        pointToM: function (lxbm,x,y,success,fail) {

            var layerUrl = "http://172.19.66.55:6080/arcgis/rest/services/COUNTYLINE/MapServer/exts/MPointConverter/pointToM";
            //   var whereStr = "?lxbm=" + lxbm + "&x=" + x + "&y=" + y;
            // layerUrl = layerUrl + whereStr;
            var layersRequest = esriRequest({
                url: layerUrl,
                content: {
                    lxbm: lxbm,
                    x: x,
                    y: y,
                    f: "json" },
                handleAs: "json",
                callbackParamName: "callback"
            });

            layersRequest.then(
                function(response) {
                    success(response)
                }, function(error) {
                    fail(error)
                });

        },

        mToPoint: function (lxbm,distance,success,fail) {
            var mToPointUrl = "http://172.19.66.55:6080/arcgis/rest/services/COUNTYLINE/MapServer/exts/MPointConverter/mToPoint";
            var mToPointProxy = esriRequest({
                url: mToPointUrl,
                content: {
                    lxbm : lxbm,
                    distance :distance,
                    f : "json"},
                handleAs: "json",
                callbackParamName: "callback"
            });
            mToPointProxy.then(function(result) {
                success(result)
            }, function (error) {
                fail(error)
            });
        },
        // selectFeature(featureLayer, id) {
        //     var query = new Query();
        //     query.where = "ID = '" + id + "'"
        //     featureLayer.selectFeatures(query, FeatureLayer.SELECTION_NEW, function (results) {
        //         if(results && results.length > 0) {
        //             var geometry = results[0].geometry
        //             switch (geometry.type) {
        //                 case 'point' :
        //                     map.centerAt(geometry);
        //                     break;
        //                 case 'polyline':
        //                     var pt = new Point(geometry.paths[0][0][0],geometry.paths[0][0][1],featureLayer.spatialReference)
        //                     map.centerAt(pt);
        //                     break;
        //                 case 'polygon':
        //                     var pt = new Point(geometry.rings[0][0][0],geometry.rings[0][0][1],featureLayer.spatialReference)
        //                     map.centerAt(pt);
        //                     break;
        //             }
        //
        //         }
        //     });
        // },
        selectFeature: function(map,featureLayer, id, symbol) {
            if(!featureLayer) {
                return;
            }
            var query = new Query();
            query.where = "ID = '" + id + "'";
            featureLayer.queryFeatures(query, function (response) {
                var feature;
                var features = response.features;
                if(features.length > 0){
                    feature = features[0];
                }
                featureLayer.selectFeatures(query, FeatureLayer.SELECTION_NEW);
                var geometry = feature.geometry;
                switch (geometry.type) {
                    case 'point' :
                        map.centerAt(geometry);
                        break;
                    case 'polyline':
                        var pt = new Point(geometry.paths[0][0][0],geometry.paths[0][0][1],featureLayer.spatialReference)
                        map.centerAt(pt);
                        break;
                    case 'polygon':
                        var pt = new Point(geometry.rings[0][0][0],geometry.rings[0][0][1],featureLayer.spatialReference)
                        map.centerAt(pt);
                        break;
                }
            });
        },
        frameSelection: function(layers, arr, callback) {
            array.map(arr, function (type) {
                if(layers[type]) {
                    layers[type].clearSelection();
                }
            });
            map.disableMapNavigation();
            var toolbar = new Draw(map);
            toolbar.activate(Draw.EXTENT);
            toolbar.on("draw-end", function (evt) {
                toolbar.deactivate();
                map.enableMapNavigation();
                var result = {};
                array.map(arr, function (type) {
                    var featureLayer = layers[type];
                    if(!featureLayer) {
                        return;
                    }
                    //进行查询
                    var query = new Query();
                    query.geometry = evt.geometry;
                    query.spatialRelationship = Query.SPATIAL_REL_CONTAINS;
                    featureLayer.queryFeatures(query, function (response) {
                        var feature;
                        var features = response.features;
                        var inBuffer = [];

                        for (var i = 0; i < features.length; i++) {
                            feature = features[i];
                            inBuffer.push(feature.attributes[featureLayer.objectIdField]);
                        }
                        var query = new Query();
                        query.objectIds = inBuffer;
                        //use a fast objectIds selection query (should not need to go to the server)
                        featureLayer.selectFeatures(query, FeatureLayer.SELECTION_NEW, function(results){
                            var re="";
                            for(var i=0;i<results.length;i++){
                                var feature = results[i];
                                re += feature.attributes["ID"]+"|";
                            }
                            result[type] = re
                        });
                    });
                });
                callback(result)
            });
        },
        measureLine :  function(toolbar){
            var attrSelectedLayer = map.graphics;
            var geometryService = new GeometryService("http://172.19.66.57:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer");
            //测量工具
            //this.toolbar = new Draw(map);
            toolbar.activate(Draw.POLYLINE);
            toolbar.on("draw-end", function(result) {
                var geometry = result.geometry;
                map.enableMapNavigation();
                toolbar.deactivate();
                //更加类型设置显示样式
                measuregeometry = geometry;
                //toolbar.deactivate();
                switch (geometry.type) {
                    case "polyline":
                        var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 0]), 2);
                        break;
                    case "polygon":
                        var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_DASH, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 0, 0.25]));
                        break;
                }
                //设置样式
                var graphic = new esri.Graphic(geometry, symbol);

                //清除上一次的画图内容
                //map.graphics.clear();
                map.infoWindow.hide();

                attrSelectedLayer.clear();
                attrSelectedLayer.add(graphic);
                //map.graphics.add(graphic);
                //进行投影转换，完成后调用projectComplete
                //如果为线类型就进行lengths距离测算

                var lengthParams = new LengthsParameters();
                lengthParams.polylines = [geometry];
                lengthParams.lengthUnit = GeometryService.UNIT_METER;
                lengthParams.geodesic = true;
                lengthParams.polylines[0].spatialReference = new esri.SpatialReference(3857);
                geometryService.lengths(lengthParams);
                dojo.connect(geometryService, "onLengthsComplete", function (result) {
                    var CurX = measuregeometry.paths[0][measuregeometry.paths[0].length - 1][0];
                    var CurY = measuregeometry.paths[0][measuregeometry.paths[0].length - 1][1];
                    var CurPos = new esri.geometry.Point(CurX, CurY, map.spatialReference);
                    map.infoWindow.setTitle("距离测量");
                    map.infoWindow.setContent(" 测量长度 ： <strong>" + parseInt(String(result.lengths[0])) + "米</strong>");
                    map.infoWindow.show(CurPos);
                })
            });
        },

        measureArea:  function(toolbar){
            var attrSelectedLayer = map.graphics;
            var geometryService = new GeometryService("http://172.19.66.57:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer");
            //测量工具
            //this.toolbar = new Draw(map);
            toolbar.activate(Draw.POLYGON);
            toolbar.on("draw-end", function(result) {
                var geometry = result.geometry;
                map.enableMapNavigation();
                toolbar.deactivate();
                //更加类型设置显示样式
                measuregeometry = geometry;
                switch (geometry.type) {
                    case "polyline":
                        var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 0]), 2);
                        break;
                    case "polygon":
                        var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_DASH, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 0, 0.25]));
                        break;
                }
                //设置样式
                var graphic = new esri.Graphic(geometry, symbol);

                //清除上一次的画图内容
                //map.graphics.clear();
                map.infoWindow.hide();

                attrSelectedLayer.clear();
                attrSelectedLayer.add(graphic);
                //如果为面类型需要先进行simplify操作在进行面积测算
                var areasAndLengthParams = new AreasAndLengthsParameters();
                areasAndLengthParams.lengthUnit = GeometryService.UNIT_METER;
                areasAndLengthParams.areaUnit = GeometryService.UNIT_SQUARE_METERS;
                this.outSR = new esri.SpatialReference({wkid: 3857});
                geometryService.project([geometry], this.outSR, function (geometry) {
                    geometryService.simplify(geometry, function (simplifiedGeometries) {
                        areasAndLengthParams.polygons = simplifiedGeometries;
                        areasAndLengthParams.polygons[0].spatialReference = new esri.SpatialReference(3857);
                        geometryService.areasAndLengths(areasAndLengthParams);
                    });
                });
                dojo.connect(geometryService, "onAreasAndLengthsComplete", function (result) {
                    var extent=measuregeometry.getExtent(); //获取查找区域的范围
                    var center=measuregeometry.getCentroid();  //获取查询区域的中心点
                    var cPoint = new esri.geometry.Point([center.x,center.y],new esri.SpatialReference({ wkid:3857 }));
                    map.infoWindow.setTitle("面积测量");
                    map.infoWindow.setContent(" 面积 ： <strong>" + parseInt(String(result.areas[0])) + "平方米</strong> 周长：" + parseInt(String(result.lengths[0])) + "米");
                    map.infoWindow.show(cPoint);
                });
            });
        }
    };
    return exports;
})